package com.example.base;

import com.example.ErrorEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler
    public ResponseDto<Object> exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        ResponseDto<Object> ob = new ResponseDto<>();
        ob.setSuccess(false);
        if(ex instanceof DemoException demoException){
            log.error("自定义异常，{}",ex.getMessage());
            ob.setErrorMessage(demoException.getMessage());
            ob.setErrorCode(demoException.code);
        }else {
            ob.setErrorCode(ErrorEnum.COMMON_ERROR.getCode());
            ob.setErrorMessage(ErrorEnum.COMMON_ERROR.getMessage());
        }

        return ob;
    }
}
